package org.coderfun.fieldmeta.web.member;

import org.coderfun.common.exception.AppException;
import org.coderfun.fieldmeta.auth.AuthService;
import org.coderfun.fieldmeta.auth.RegisterService;
import org.coderfun.fieldmeta.common.EmailCaptchaService;
import org.coderfun.member.core.exception.MemberErrorCode;
import org.coderfun.member.core.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import klg.common.model.JsonData;

@RestController
@RequestMapping("/member")
public class MemberController {
	
	@Autowired
	AuthService authService;
	
	@Autowired
	RegisterService registerService;
	
	@Autowired
	MemberService memberService;
	
	@Autowired
	EmailCaptchaService captchaService;
	

	@PostMapping("/login")
	public JsonData login(String email,String password){
		
		authService.login(email, password);
		return JsonData.success();
	}
	
	@GetMapping("/logout")
	public JsonData logout(){
		authService.logout();
		return JsonData.success();
	}
	
	@PostMapping("/sendCaptcha")
	public JsonData sendCaptcha(String email){
		if(!memberService.checkEmailExist(email)){
			throw new AppException(MemberErrorCode.USER_NOT_EXIST);
		}
		captchaService.send(email);
		return JsonData.success();
	}
	
	@PostMapping("/sendRegisterCaptcha")
	public JsonData sendRegisterCaptcha(String email){
		if (memberService.checkEmailExist(email)) {
			throw new AppException(MemberErrorCode.USER_EMAIL_EXIST);
		}
		captchaService.send(email);
		return JsonData.success();
	}

	@PostMapping("/register")
	public JsonData register(
			@RequestParam String username,
			@RequestParam String email, 
			@RequestParam String password, 
			@RequestParam String captcha){
		registerService.register(username, email, password, captcha);
		return JsonData.success();
	}
	
	@PostMapping("/resetPassword")
	public JsonData resetPassword(
			@RequestParam String email, 
			@RequestParam String password, 
			@RequestParam String captcha){
		registerService.resetPassword(email, password, captcha);
		return JsonData.success();
	}
	
	@PostMapping("/changeWorkspace")
	public JsonData changeWorkspace(Long workspaceId){
		authService.changeWorkspace(workspaceId);
		return JsonData.success();
	}
	
}
